const Redis = require("@/utils/redis");
const { ErrorCode } = require("@/utils/r/code");
// 定义常量
const KEY_USER = "user:";
const KEY_DELETE = "delete:";

function listen_online() {
  return async (req, res, next) => {
    const uuid = req["uuid"];
    const userKey = KEY_USER + uuid;
    let s = await Redis.GetResult(userKey);

    let sessionInfo;
    if (s) {
      sessionInfo = s;
    } else {
      s = await Redis.GetResult(KEY_DELETE + uuid);
      if (s) {
        sessionInfo = s;
      } else {
        sessionInfo = req.session.sessionInfo;
      }
    }

    if (sessionInfo && sessionInfo.isOffline === 1) {
      await Redis.Del(userKey);
      Reflect.has(req.session[userKey]) && delete req.session[userKey];
      req.session.save((e) => {
        console.log("删除session值失败", e);
      });
      return res.status(401).json({ error: ErrorCode.FORCE_OFFLINE });
    }

    await Redis.Set(userKey, sessionInfo, 600);

    next();
  };
}

module.exports = listen_online;
